//
//  FWWorkFormViewController.m
//  Patrol
//
//  Created by 范武 on 13-2-28.
//  Copyright (c) 2013年 FSTI. All rights reserved.
//

#import "FWWorkFormViewController.h"
#import "FormData.h"
#import "PatrolServiceClient.h"
#import "MBProgressHUD.h"
#import "FWAppDelegate.h"
#import "TTSwitch.h"
#import "PictureTakingController.h"
#import <CoreLocation/CoreLocation.h>
#import "FWAppDelegate.h"
#import "ShakeQueryViewController.h"

#define kDefaultLabelLength 120.0f
#define kDefaultRadioLabelLength 160.0f

#define kPicViewHeight 97.0f
//默认Radio前面那个label的大小最多放15个字 默认字体 17
#define kMaxRadioLabelCharCount 15
#define kDefaultLabelHeight     21.0f

#define kdescLabelWidth 280.0f
#define kdescLabelHeight 20.0f
#define kDefaultCellHeight 44.0f   

@interface FWWorkFormViewController ()
{
    FormData * form;
    PictureTakingController * picTakeVC;
    BOOL isPickViewCollapse;
    CLLocationManager * locationManager;
    UIButton * submit;
    NSMutableArray * textInputControls;
    MTStatusBarOverlay *overlay;
    FWAppDelegate *delegate;
}

@end


@implementation FWWorkFormViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"作业单详情";
        picTakeVC = [[PictureTakingController alloc]initWithNibName:@"PictureTakingController" bundle:nil];
        [picTakeVC.view.po_frameBuilder setHeight:0];
        isPickViewCollapse = YES;
        [self addChildViewController:picTakeVC];
        
        locationManager = [CLLocationManager new];
        [locationManager startUpdatingLocation];
    }
    return self;
}

- (void)viewWillDisappear:(BOOL)animated{
    [overlay postImmediateFinishMessage:@"" duration:0 animated:YES];
}

#pragma mark - json Services

/**
 *  调用后台接口来加载工作单信息
 */
- (void)callService
{
    PatrolServiceClient * client = [PatrolServiceClient shareInstance];
    
    NSString * username = delegate.userName;

    [MBProgressHUD showHUDAddedTo:self.scrollView animated:YES].labelText = @" 正在加载工单";
    if (client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi || client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
        [client getUser:username Work:_workID resultBlock:^(id outJson, NSError *error) {
            [MBProgressHUD hideAllHUDsForView:self.scrollView animated:YES];
            if (!outJson && error) {
                ALog(@"调用后台生成form窗体出现错误: %@", error);
                [UIUtil alertOKWithTitle:@"错误" withMsg:@"后台服务出现错误，请稍后再试" withDelegate:nil];
                return ;
            }
            DLog(@"json Data:%@",outJson);
            
            NSDictionary * formJson = outJson;
            
            form = [[FormData alloc] initWithDictonary:formJson];
            DLog(@"form: %@", form.description);
            [self buildForm];
        }];
    }else{
        [UIUtil alertOKWithTitle:@"错误" withMsg:@"当前没有连接到任何网络，无法提交数据" withDelegate:nil];
    }
}

#pragma mark - 表单处理

- (void) submitForm:(id)sender
{
    PatrolServiceClient * client = [PatrolServiceClient shareInstance];
    NSString * username = delegate.userName;
    NSInteger taskID = form.taskID;
    CLLocationCoordinate2D gpsCoordinate = [self getCurrentGPSLocation];
    NSArray * formData = [form getUserInputJson];
    
    if (![form isUserInputAllTheNessaryFields]) {
        [UIUtil alertOKWithTitle:@"输入错误" withMsg:@"必填字段未填写" withDelegate:nil];
        return;
    }
    if (client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWiFi || client.networkReachabilityStatus == AFNetworkReachabilityStatusReachableViaWWAN) {
        [MBProgressHUD showHUDAddedTo:_scrollView animated:YES].labelText = @"正在提交表单信息";
        [client submitWork:username task:taskID location:gpsCoordinate formValues:formData resultBlock:^(id outJson, NSError *error) {
            [MBProgressHUD hideAllHUDsForView:_scrollView animated:YES];
            NSInteger result_code = [outJson[@"result_code"] integerValue];
            NSString * result_desc = outJson[@"result_desc"];
            //这个值虽然服务器有返回，但是目前没什么用
//            NSInteger track_code = [outJson[@"track_code"] integerValue];
            NSString * track_desc = outJson[@"track_desc"];
            
            NSString * desc = [NSString stringWithFormat:@"%@ \r\n %@",result_desc,track_desc];
            

            
            if (result_code == 1) {
                [UIUtil alertOKWithTitle:@"数据提交成功" withMsg:desc withDelegate:self];
            }else{
                [UIUtil alertOKWithTitle:@"提交失败" withMsg:desc withDelegate:nil];
            }
        }];
        
        //upload pic
        [picTakeVC uploadPicturesWorkTask:taskID username:username];
    }else{
        [UIUtil alertOKWithTitle:@"错误" withMsg:@"当前没有连接到任何网络，无法提交数据" withDelegate:nil];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //  回到作业计划
//    FWAppDelegate * delegate = [[UIApplication sharedApplication] delegate];
//    ShakeQueryViewController * shakeVC = delegate.shakeQueryViewController;
//    [self.navigationController popToViewController:shakeVC animated:YES];
    [self.navigationController popViewControllerAnimated:YES];
}




#pragma mark - Get GPS Location
- (CLLocationCoordinate2D ) getCurrentGPSLocation
{
    CLLocationCoordinate2D coodinate = locationManager.location.coordinate;
    if (CLLocationCoordinate2DIsValid(coodinate)) {
        return coodinate;
    }else{
        coodinate = CLLocationCoordinate2DMake(delegate.latitude, delegate.longitude);
        if (CLLocationCoordinate2DIsValid(coodinate)) {
            return coodinate;
        }else{
            [UIUtil alertOKWithTitle:@"错误！" withMsg:@"无法获取正确的GPS坐标信息" withDelegate:nil];
            return CLLocationCoordinate2DMake(0, 0);
        }
    }
}

#pragma mark - Form Builder

- (void) buildForm
{
    [self setContent:form.deviceName label:_deviceNameLabel labelFont:[UIFont systemFontOfSize:22]];
    [self setContent:form.planName label:_planNameLabel labelFont:[UIFont systemFontOfSize:15]];
    CGPoint devicePoint = _deviceNameLabel.frame.origin;
    CGSize deviceSize = _deviceNameLabel.frame.size;
    CGSize planSize = _planNameLabel.frame.size;
    [_planNameLabel setFrame:CGRectMake(devicePoint.x, devicePoint.y + deviceSize.height + 5, planSize.width, planSize.height)];
    CGFloat offset = 30.0f + deviceSize.height + planSize.height;
    for (FormField * field in form.fieldData) {

        UIView * view = [self buildField:field];
        
        [view.po_frameBuilder moveWithOffsetY:offset];
        [self.scrollView addSubview:view];
      
        offset += CGRectGetHeight(view.frame);

    }
    UIView * cameraView = [self buildCameraField];
    [cameraView.po_frameBuilder moveWithOffsetY:offset];
    [self.scrollView addSubview:cameraView];
    offset += 44.0f;
    
    
    self.scrollView.contentSize = CGSizeMake(320, offset);
    offset += 20.0f;
    //add PicTake
    [picTakeVC.view.po_frameBuilder moveWithOffsetY:offset];
    [_scrollView addSubview:picTakeVC.view];
    
    //添加最后的提交按钮
    
    submit = [UIButton buttonWithType:UIButtonTypeCustom];
    submit.frame = CGRectMake(180, offset + 20, 100, 40);
    [submit setTitle:@"提 交" forState:UIControlStateNormal];
    [submit setBackgroundImage:[UIImage imageNamed:@"login1"] forState:UIControlStateNormal];
    [submit.po_frameBuilder setOriginWithX:180 y:offset + 20];
    [submit addTarget:self action:@selector(submitForm:) forControlEvents:UIControlEventTouchUpInside];
    [_scrollView insertSubview:submit belowSubview:picTakeVC.view];
    
    offset += 80.0f;
    [_scrollView setContentSize:CGSizeMake(320, offset)];
    
//    DLog(@"The View:%@",self.view);
}

- (UIView *) buildField:(FormField *) field
{
    UIView * fieldView;
    switch (field.type) {
        case radio:
            fieldView = [self buildRadioField:field];
            break;
        case textField:
            fieldView = [self buildTextField:field];
            break;
        case textView:
            fieldView = [self buildTextViewField:field];
            break;
            
    }
    return fieldView;
}

- (UIView *) buildCameraField
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
    UILabel * label = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, kDefaultLabelLength, 21)];
    label.text = @"拍照:";
    UIButton * camera = [UIButton buttonWithType:UIButtonTypeCustom];
    [camera setBackgroundImage:[UIImage imageNamed:@"camera_40"] forState:UIControlStateNormal];
    camera.frame = CGRectMake(200, 12, 40, 40);
    [camera addTarget:self action:@selector(presentCameraView:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:label];
    [view addSubview:camera];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(presentCameraView:)];
    [view addGestureRecognizer:tap];
    
    return view;
}

- (UIView *) buildTextField:(FormField *)textField
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, kDefaultLabelLength, kDefaultLabelHeight)];
    CGFloat diff = [FWWorkFormViewController calcLabel:label diffHeightWithString:textField.title];
    [view.po_frameBuilder setHeight:(CGRectGetHeight(view.frame) + diff)];
    [view addSubview:label];
    
    
    
    UITextField * field = [[UITextField alloc] initWithFrame:CGRectMake(172, 17, 132, 30)];
    field.delegate = self;
    field.borderStyle = UITextBorderStyleRoundedRect;
    if (textField.notNull) {    //据@魏莹说，此种情况其实目前都未出现，所有的必填字段全是Radio，也就是Switch
        field.placeholder = @"必填";
    }
    field.returnKeyType = UIReturnKeyNext;
    textField.fieldControl = field;
    [view addSubview:field];
    
    [textInputControls addObject:field];
    
    [label.po_frameBuilder centerVerticallyInSuperview];
    [field.po_frameBuilder centerVerticallyInSuperview];
    
    return view;
}

- (UIView * ) buildTextViewField:(FormField *)textViewField
{
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 170)];
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, kDefaultLabelLength, 21)];
    CGFloat diff = [FWWorkFormViewController calcLabel:label diffHeightWithString:textViewField.title];
    [view addSubview:label];
    [view.po_frameBuilder setHeight:(diff + CGRectGetHeight(view.frame))];
    
    UITextView * textView = [[UITextView alloc]initWithFrame:CGRectMake(172, 20, 132, 128)];
    textView.layer.borderColor = [UIColor darkGrayColor].CGColor;
    textView.layer.borderWidth = 1.0f;
    textView.layer.cornerRadius = 5.0f;
    textView.layer.shadowColor = [UIColor blackColor].CGColor;
    textView.delegate = self;
    textViewField.fieldControl = textView;
    [view addSubview:textView];
    
    [textInputControls addObject:textView];
    
    [label.po_frameBuilder centerVerticallyInSuperview];
    [textView.po_frameBuilder centerVerticallyInSuperview];
    
    return view;
}

- (UIView *) buildRadioField:(FormField *)radioField
{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 44)];

    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(20, 20, kDefaultRadioLabelLength, kDefaultLabelHeight)];
    CGFloat diff = [FWWorkFormViewController calcLabel:label diffHeightWithString:radioField.title];
    [view addSubview:label];
    
    [view.po_frameBuilder setHeight:(CGRectGetHeight(view.frame) + diff)]; //因为label变高，所以view也相应变高
    
    //setsup switch
    TTSwitch * _switch = [[TTSwitch alloc] initWithFrame:(CGRect){ {220,17}, { 76.0f, 28.0f } }];
    _switch.on = YES;
    [view addSubview:_switch];
    
    [_switch.po_frameBuilder centerVerticallyInSuperview];

    radioField.fieldControl = _switch;
    



    return view;
}

+ (CGFloat)calcLabel:(UILabel *)label diffHeightWithString:(NSString *) strContent
{
    static UIFont * labelFont = nil;
    if (!labelFont) {
        labelFont = [UIFont systemFontOfSize:17];
    }
    //prepare
    label.lineBreakMode = UILineBreakModeWordWrap;
    label.numberOfLines = 0;
    
    //calc
    CGFloat width = CGRectGetWidth(label.frame);
    CGFloat height = CGRectGetHeight(label.frame);
    CGSize constrained_label_size = CGSizeMake(width, CGFLOAT_MAX);
    CGSize labelSize = [strContent sizeWithFont:labelFont constrainedToSize:constrained_label_size lineBreakMode:UILineBreakModeWordWrap];
    //set
    [label.po_frameBuilder setHeight:labelSize.height];
    label.text = strContent;
    
    //return the diff
    return labelSize.height - height;
}

- (void)presentCameraView:(id)sender
{
    CGFloat oldHeight = _scrollView.contentSize.height;
    [UIView animateWithDuration:0.50f animations:^{
        if (isPickViewCollapse) {
            [picTakeVC.view.po_frameBuilder setHeight:kPicViewHeight];
            [submit.po_frameBuilder moveWithOffsetY:kPicViewHeight];
            [_scrollView setContentSize:CGSizeMake(320, oldHeight + kPicViewHeight)];
            [_scrollView setContentOffset:CGPointMake(0, oldHeight - 200) animated:YES];
            isPickViewCollapse = NO;
        }else{
            [picTakeVC.view.po_frameBuilder setHeight:0];
            [submit.po_frameBuilder moveWithOffsetY:-kPicViewHeight];
            [_scrollView setContentSize:CGSizeMake(320, oldHeight - kPicViewHeight)];
            [_scrollView setContentOffset:CGPointMake(0, oldHeight - kPicViewHeight - 200) animated:YES];
            isPickViewCollapse = YES;
        }
    }];
}

- (void)showGpsToStatusBar{
    overlay = [MTStatusBarOverlay sharedInstance];
    overlay.animation = MTStatusBarOverlayAnimationFallDown;
    overlay.detailViewMode = MTDetailViewModeHistory;
    overlay.delegate = delegate;
    CLLocationCoordinate2D coordinate = [self getCurrentGPSLocation];
    NSString *message = [NSString stringWithFormat:@"经度:%f 纬度:%f",coordinate.longitude,coordinate.latitude];
    [overlay postImmediateFinishMessage:message duration:60.0 animated:YES];
    overlay.progress = 1.0;
}

#pragma mark - inherit Funcation

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    
    delegate = (FWAppDelegate *)[UIApplication sharedApplication].delegate;
    
    [self callService];
    
    [self showGpsToStatusBar];
    
    UITapGestureRecognizer * tapGestureReco = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(backgroundTap:)];
    [self.view addGestureRecognizer:tapGestureReco];
    
    textInputControls = [NSMutableArray arrayWithCapacity:form.fieldData.count];
}

- (void)backgroundTap:(UITapGestureRecognizer *)reco
{
    [[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
}


- (void)didReceiveMemoryWarning
{
    [self destruct];
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    [self destruct];
    [super viewDidUnload];
}

- (void)destruct
{
//    [self setDeviceNameLabel:nil];
//    [self setScrollView:nil];
//    [locationManager stopUpdatingLocation];
//    submit = nil;
//    form = nil;
//    [textInputControls removeAllObjects];
//    textInputControls = nil;
}

#pragma mark textField delegate
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    CGFloat y = textField.superview.frame.origin.y - 80;
    [_scrollView setContentOffset:CGPointMake(0, y) animated:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    for (int i = 0; i< textInputControls.count; ++i) {
        id input = textInputControls[i];
        if (input !=nil && input == textField) {
            [textField resignFirstResponder];

            if (i+1 < textInputControls.count) {
                input = textInputControls[i+1];
                [input becomeFirstResponder];
            }else{
                [submit becomeFirstResponder];
            }
            return YES;
        }
    }
    [submit becomeFirstResponder];
    return YES;
}

#pragma mark textView delegate
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    CGFloat y = textView.superview.frame.origin.y - 100;
    [_scrollView setContentOffset:CGPointMake(0, y) animated:YES];
}

#pragma mark -
#pragma setLabelContent
- (void)setContent:(NSString * ) content label:(UILabel *)label labelFont:(UIFont *)labelFont
{
    label.text = content;
    CGFloat actualHeight = [FWWorkFormViewController calcLabelHeightForString:content labelFont:labelFont];
    if (actualHeight <= kdescLabelHeight) {
        return ;
    }else{
        [label.po_frameBuilder setHeight:actualHeight];
    }
}
+ (CGFloat) calcLabelHeightForString:(NSString * )content labelFont:(UIFont *)labelFont
{
    static CGSize constrainedSize = {kdescLabelWidth, CGFLOAT_MAX};
    CGFloat height =  [content sizeWithFont:labelFont constrainedToSize:constrainedSize lineBreakMode:UILineBreakModeWordWrap].height;
    return height;
}
@end
